package tasks

import (
	"fmt"
	"log"
	"mediumkube/pkg/common"
	"mediumkube/pkg/network"
	"mediumkube/pkg/procd"
	"mediumkube/pkg/utils"
	"os"
	"path"
	"strings"
	"time"

	"github.com/vishvananda/netlink"
	"k8s.io/klog/v2"
)

const (
	dnsMasqExecutable = "mediumkube-dnsmasq"
)

func dhcpRange(config *common.OverallConfig) string {
	if !config.Overlay.Enabled {
		from, to, err := network.CidrIPRange(config.Bridge.Inet)
		utils.CheckErr(err)
		return fmt.Sprintf("%s,%s", from, to)
	}

	from, to, err := network.CidrIPRange(config.Overlay.Cidr)
	utils.CheckErr(err)
	return fmt.Sprintf("%s,%s", from, to)

}

func NewDNSMasqTask(config *common.OverallConfig) *procd.DaemonCmdTask {
	timeout := 100
	counter := 0
	bridge := config.Bridge
	for {
		if counter == timeout {
			break
		}
		counter++
		_, err := netlink.LinkByName(bridge.Name)
		if err != nil {
			_, ok := err.(netlink.LinkNotFoundError)
			if ok {
				klog.Info("Waiting for bridge to be created")
			}
			log.Println(err)
		} else {
			break
		}
		time.Sleep(1 * time.Second)
	}

	leaseFile := path.Join(config.TmpDir, "dnsmasq.lease")
	t := procd.NewDaemonCmdTask(dnsMasqExecutable,
		"--keep-in-foreground",
		"--strict-order",
		"--bind-interfaces",
		"--pid-file",
		"--domain=mediumkube",
		"--local=/mediumkube/",
		"--except-interface=lo",
		"--interface", bridge.Name,
		fmt.Sprintf("--listen-address=%v", strings.Split(bridge.Inet, "/")[0]),
		"--dhcp-no-override",
		"--dhcp-authoritative",
		// NEVER change lease file.
		fmt.Sprintf("--dhcp-leasefile=%v", leaseFile),
		fmt.Sprintf("--dhcp-range=%v", dhcpRange(config)))
	t.AttachWriterToStdout(os.Stdout)
	return t
}
